import { onMounted, ref, computed, onBeforeUnmount } from "vue";
import { getTime, setTime } from "@/request";
export const useTime = () => {
   const WEEK = ["日", "一", "二", "三", "四", "五", "六"];

   // 分割时间
   const timeSpliter = (time?: string | number): Array<number> => {
      const current: Date = time ? new Date(time) : new Date();
      const YYYY = current.getFullYear();
      const MM = current.getMonth() + 1;
      const DD = current.getDate();
      const hh = current.getHours();
      const mm = current.getMinutes();
      const ss = current.getSeconds();
      const week = current.getDay();
      return [YYYY, MM, DD, hh, mm, ss, week];
   };

   // 填充零
   const zeroPadder = (value: number | string): string => {
      return value > 9 ? value.toString() : "0" + value;
   };

   // 时间格式化
   const timeFormater = (format: string, time?: string | number): string => {
      const [YYYY, MM, DD, hh, mm, ss, week] = timeSpliter(time);
      const result = format
         .replace("YYYY", `${zeroPadder(YYYY)}`)
         .replace("MM", `${zeroPadder(MM)}`)
         .replace("DD", `${zeroPadder(DD)}`)
         .replace("hh", `${zeroPadder(hh)}`)
         .replace("mm", `${zeroPadder(mm)}`)
         .replace("ss", `${zeroPadder(ss)}`)
         .replace("WEEK", `星期${WEEK[week]}`);
      return result;
   };

   // 动态
   const timeStamp = ref();
   const time = computed(() =>{
      return timeFormater("YYYY.MM.DD-hh:mm:ss", timeStamp.value)
   }   
   );
   // 同步时间
   const refreshTime = async () => {
      getTime().then(data=>{    
         if(data){
            timeStamp.value = new Date(data.time).getTime();
         }else{
            timeStamp.value = new Date().getTime();
         }
      })
   };
   // 自增
   const timerAdder = () => {
      timeStamp.value += 1000;
   };


   const Timer:{[index:string]:any}={
      sysTimer:null,
      localTimer:null
   }

  
  const clearSysTimer=()=>{
      clearInterval(Timer.sysTimer)
      clearInterval(Timer.localTimer)
  }
   onMounted(() => {
      clearSysTimer()
      refreshTime();
      if(!Timer.localTimer){
         Timer.localTimer= setInterval(() => {
               timerAdder();
         }, 1000);
      }
      if(!Timer.sysTimer){
         Timer.sysTimer= setInterval(() => {
               refreshTime();
         }, 1000 * 60 * 5);
      }
   });

   onBeforeUnmount(() => {
      clearSysTimer()
   });

   return {
      timeStamp,
      timeSpliter,
      timeFormater,
      zeroPadder,
      time,
      setTime,
      refreshTime,
   };
};
